package view;
import java.awt.*;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Component;
import javax.swing.*;
import utils.Tools;
import java.awt.Dimension;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class StudentListView {
    private JFrame frame;
    private final int WIDTH = 600;    // 加宽窗口以便显示列表
    private final int HEIGHT = 400;
    private JPanel listPanel;         // 用于显示学生列表的面板

    public StudentListView() {
        // 修改窗口标题为"学生列表"
        frame = new JFrame("学生列表");
        initView();
        frame.setLayout(null);
        frame.setResizable(false);
        Tools.setPos(frame, WIDTH, HEIGHT);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.setVisible(true);
    }

    private void initView() {
        // 创建标题标签
        JLabel titleLabel = new JLabel("当前所有学生", SwingConstants.CENTER);
        titleLabel.setBounds(0, 20, WIDTH, 30);
        titleLabel.setFont(new Font("宋体", Font.BOLD, 16));
        frame.add(titleLabel);

        // 创建滚动面板来容纳学生列表
        listPanel = new JPanel();
        //y轴滚动布局
        listPanel.setLayout(new BoxLayout(listPanel, BoxLayout.Y_AXIS));
        JScrollPane scrollPane = new JScrollPane(listPanel);
        scrollPane.setBounds(50, 60, WIDTH-100, HEIGHT-150);
        frame.add(scrollPane);

        // 加载并显示学生列表
        loadStudentList();

        // 创建返回按钮
        JButton backBtn = new JButton("返回主页");
        backBtn.setBounds(WIDTH/2-50, HEIGHT-70, 100, 30);
        backBtn.addActionListener(e -> {
            frame.dispose();
            new MainView();
        });
        frame.add(backBtn);
    }

    // 加载学生列表
    private void loadStudentList() {
        try {
            File file = new File("resources/Student.txt");
            if (!file.exists()) {
                JLabel noDataLabel = new JLabel("暂无学生信息");
                //组件水平居中显示
                noDataLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
                listPanel.add(noDataLabel);
                return;
            }

            BufferedReader br = new BufferedReader(new FileReader(file));
            String StudentName;
            while ((StudentName = br.readLine()) != null) {
                if (!StudentName.trim().isEmpty()) {
                    //显示学生
                    addStudentItem(StudentName.trim());
                }
            }
            br.close();

        } catch (IOException e) {
            JOptionPane.showMessageDialog(frame, "读取学生信息失败：" + e.getMessage(),
                    "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    // 为每个学生创建显示项
    private void addStudentItem(String studentInfo) {
        // 解析学生信息：学号,姓名,小组
        String[] parts = studentInfo.split(",");
        if (parts.length < 3) return;

        String studentId = parts[0].trim();
        String studentName = parts[1].trim();
        String groupName = parts[2].trim();

        // 创建单个学生项的面板
        JPanel itemPanel = new JPanel();
        itemPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        itemPanel.setMaximumSize(new Dimension(WIDTH-120, 40));

        // 学号标签
        JLabel idLabel = new JLabel("学号: " + studentId);
        idLabel.setPreferredSize(new Dimension(100, 30));

        // 姓名标签
        JLabel nameLabel = new JLabel("姓名: " + studentName);
        nameLabel.setPreferredSize(new Dimension(100, 30));

        // 小组标签
        JLabel groupLabel = new JLabel("小组: " + groupName);
        groupLabel.setPreferredSize(new Dimension(100, 30));

        // 删除按钮
        JButton deleteBtn = new JButton("删除");
        deleteBtn.addActionListener(e -> deleteStudent(studentId, itemPanel));

        // 添加组件到面板
        itemPanel.add(idLabel);
        itemPanel.add(nameLabel);
        itemPanel.add(groupLabel);
        itemPanel.add(deleteBtn);
        listPanel.add(itemPanel);
        listPanel.revalidate();
    }

    // 删除学生
    private void deleteStudent(String studentId, JPanel itemPanel) {
        int confirm = JOptionPane.showConfirmDialog(frame,
                "确定要删除该学生吗？",
                "确认删除",
                JOptionPane.YES_NO_OPTION);

        if (confirm == JOptionPane.YES_OPTION) {
            try {
                List<String> students = new ArrayList<>();
                BufferedReader br = new BufferedReader(new FileReader("resources/Student.txt"));
                String line;
                while ((line = br.readLine()) != null) {
                    String[] parts = line.split(",");
                    if (parts.length > 0 && !parts[0].trim().equals(studentId)) {
                        students.add(line);
                    }
                }
                br.close();

                BufferedWriter bw = new BufferedWriter(new FileWriter("resources/Student.txt"));
                for (String student : students) {
                    bw.write(student);
                    bw.newLine();
                }
                bw.close();

                listPanel.remove(itemPanel);
                listPanel.revalidate();
                listPanel.repaint();

                JOptionPane.showMessageDialog(frame, "删除成功！");
            } catch (IOException e) {
                JOptionPane.showMessageDialog(frame, "删除失败：" + e.getMessage(),
                        "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
}

